package cc.siyecao.mapper;

import cc.siyecao.mapper.enums.SqlConstants;
import cc.siyecao.mapper.enums.SqlKeyword;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Criteria {
    protected List<Criterion> criterionList;

    private final Map<String, Criterion> criterionMap = new HashMap<>();

    protected String type = "normal";

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    public Criteria() {
        this.criterionList = new ArrayList<>();
    }

    public Criteria(String type) {
        this.criterionList = new ArrayList<>();
        this.type = type;
    }

    public void addCriterion(String condition) {
        criterionList.add( new Criterion( condition ) );
    }

    public void addCriterion(String condition, Object value) {
        if (value == null) {
            throw new RuntimeException( "Value for " + condition + " cannot be null" );
        }
        criterionList.add( new Criterion( condition, value ) );
    }

    private void addCriterion(String column, Criterion criterion) {
        Criterion oldCriterion = criterionMap.get( column );
        if (oldCriterion != null) {
            criterionList.remove( oldCriterion );
        }
        criterionMap.put( column, criterion );
        criterionList.add( criterion );
    }

    public void addCriterion(String column, SqlKeyword sqlKeyword) {
        addCriterion( column, new Criterion( columnToCondition( column, sqlKeyword ) ) );
    }

    public void addCriterion(String column, SqlKeyword sqlKeyword, Object value) {
        if (value == null) {
            throw new RuntimeException( "Value for " + column + " cannot be null" );
        }
        addCriterion( column, new Criterion( columnToCondition( column, sqlKeyword ), value ) );
    }

    public void addCriterion(String column, SqlKeyword sqlKeyword, Object value1, Object value2) {
        if (value1 == null || value2 == null) {
            throw new RuntimeException( "Between values for " + column + " cannot be null" );
        }
        addCriterion( column, new Criterion( columnToCondition( column, sqlKeyword ), value1, value2 ) );
    }

    private String columnToCondition(String column, SqlKeyword sqlKeyword) {
        return column + SqlConstants.SPACE + sqlKeyword.getKeyword() + SqlConstants.SPACE;
    }

    public List<Criterion> getCriterionList() {
        return criterionList;
    }

    public Map<String, Criterion> getCriterionMap() {
        return criterionMap;
    }

    public boolean isValid() {
        return criterionList.size() > 0;
    }

    public void clear() {
        criterionList.clear();
        type = "normal";
    }


}
